package net.weamor.ichat.listener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class FileDeleteTimer implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent sce) {

	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		Timer timer = new Timer();
		//延迟一秒执行，每一天执行一次
		timer.schedule(new DeleteTask(), 1 * 1000,1000 * 60 * 60 *24);
	}

}

class DeleteTask extends TimerTask{

	@Override
	public void run() {
		/*
		 * find /opt/Oracle/admin/CCXE/bdump/ -mtime +10 -name "*.*" -exec rm -Rf {} \;
		 * 
		 * /opt/Oracle/admin/CCXE/bdump/ ：想要进行清理的任意目录
	 
			-mtime：标准语句写法
			＋10：查找10天前的文件，这里用数字代表天数，＋30表示查找30天前的文件
			 
			"*.*"：希望查找的数据类型，"*.jpg"表示查找扩展名为jpg的所有文件，"*"表示查找所有文件
			-exec：固定写法
			 
			rm -rf：强制删除文件，包括目录
			 {} \; ：固定写法，一对大括号+空格+/+;
		 * 
		 */
		//请更改存储路径
		String fileSavePath = "/opt/Oracle/admin/CCXE/bdump/";
		String cmd = "find "+ fileSavePath +" -mtime +2 -name *.* -exec rm -Rf {} /";
		String[] cmds = { "/bin/sh", "-c", cmd };
		Process pro;
		try {
			pro = Runtime.getRuntime().exec(cmds);
			pro.waitFor();
			InputStream in = pro.getInputStream();
			BufferedReader read = new BufferedReader(new InputStreamReader(in));
			String line = null;
			while ((line = read.readLine()) != null) {
				System.out.println(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
	
}
